﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace RestaurantManagerWebApp.Pages.TableManagement
{
    public partial class MainTableManagement : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            //testingcommit
            try
            {
                int tablesAdding = Convert.ToInt32(Request.QueryString["table"]);
                //bool tablesAdded = Convert.ToBoolean(Request.QueryString["tablesAdded"]);
                int tablesAmount = Convert.ToInt32(Request.QueryString["tablesAmount"]);
                int tablesFailed = Convert.ToInt32(Request.QueryString["tablesFailed"]);
                bool photo = Convert.ToBoolean(Request.QueryString["photo"]);

                if (tablesAdding != 0)
                {
                    Label3.Visible = true;
                    Label4.Visible = true;
                    Label5.Visible = true;
                    Label7.Visible = true;

                    for (int i = 1; i <= tablesAdding; i++)
                    {
                        TextBox tName = new TextBox();
                        TextBox tStatus = new TextBox();
                        TextBox tCapacity = new TextBox();
                        TextBox tCat = new TextBox();
                        tName.ID = "textBoxName" + i.ToString();
                        tStatus.ID = "textboxStatus" + i.ToString();
                        tStatus.Text = "Available";
                        tStatus.ReadOnly = true;
                        tCapacity.ID = "textBoxCapacity" + i.ToString();
                        tCat.ID = "textBoxCat" + i.ToString();
                        autoGenTextbox.Controls.Add(tName);
                        autoGenTextbox0.Controls.Add(tStatus);
                        autoGenTextbox1.Controls.Add(tCapacity);
                        autoGenTextbox2.Controls.Add(tCat);
                        tName.Focus();
                    }

                    //TextBox c = (TextBox)Page.FindControl("textBoxName1");
                    //c.Focus();

                }

                if (tablesAmount > 0)
                {
                    labelStatus.Visible = true;
                    labelStatus.Text = tablesAmount + " tables added successfully. ";
                }
                if (tablesFailed > 0)
                {
                    labelStatus.Visible = true;
                    labelStatus.Text = labelStatus.Text + "Total of " + tablesFailed + " tables failed to be added. ";
                }

                if (photo == true)
                {
                    lblUploadStatus.Visible = true;
                    lblUploadStatus.Text = "Your file was uploaded successfully.";
                    uploadLayout.Focus();
                }
            }
            catch
            {

            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            conn.Open();

            try
            {
                int tablesAdding = Convert.ToInt32(Request.QueryString["table"]);
                int tablesAdded = 0;
                int tablesFailed = 0;
                int[] capArray;
                capArray = new int[29];
                string[] catArray;
                catArray = new string[29];
                int arrayCount = 0;
                bool proceed = false;

                foreach (Control c in autoGenTextbox.Controls)
                {
                    TextBox t = (TextBox)c;

                    if (t.Text != "")
                    { 
                        proceed = true; 
                    }
                    else
                    {
                        proceed = false;
                        Response.Write("<script type=\"text/javascript\">alert('Please assign a table no for every tables to be created.');</script>");
                    }
                }

                foreach (Control c in autoGenTextbox1.Controls)
                {
                    TextBox t = (TextBox)c;

                    if (t.Text != "")
                    {
                        proceed = true;
                        capArray[Convert.ToInt32(arrayCount)] = Convert.ToInt32(t.Text);
                        arrayCount++;
                    }
                    else
                    {
                        proceed = false;
                        Response.Write("<script type=\"text/javascript\">alert('Please state the capacity for every tables to be created.');</script>");
                    }
                }
                arrayCount = 0;

                foreach (Control c in autoGenTextbox2.Controls)
                {
                    TextBox t = (TextBox)c;

                    if (t.Text != "")
                    {
                        proceed = true;
                        catArray[Convert.ToInt32(arrayCount)] = t.Text;
                        arrayCount++;
                    }
                    else
                    {
                        proceed = true;
                        catArray[Convert.ToInt32(arrayCount)] = "";
                    }
                }
                arrayCount = 0;

                if (proceed == true)
                {
                    foreach (Control c in autoGenTextbox.Controls)
                    {
                        TextBox t = (TextBox)c;
                        string table_no = t.Text;

                        string checkDupTable = "SELECT table_no FROM Tables WHERE table_no = @table_no;";
                        SqlCommand checkDup = new SqlCommand(checkDupTable, conn);
                        checkDup.Parameters.AddWithValue("@table_no", table_no);
                        SqlDataReader dr = checkDup.ExecuteReader();

                        if (dr.HasRows == false)
                        {
                            dr.Close();
                            cmd.CommandText = "INSERT INTO Tables VALUES (@table_no, 'Available', @capacity, @cat);";
                            cmd.Parameters.AddWithValue("@table_no", table_no);
                            cmd.Parameters.AddWithValue("@capacity", capArray[Convert.ToInt32(arrayCount)]);
                            cmd.Parameters.AddWithValue("@cat", catArray[Convert.ToInt32(arrayCount)]);
                            int affectedRows = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                            tablesAdded++;
                        }
                        else
                        {
                            tablesFailed++;
                            dr.Close();
                        }
                        arrayCount++;
                    }
                    //Response.Redirect("TableManagement.aspx?tablesAdded=true&tablesAmount=" + tablesAdded + "&tablesFailed=" + tablesFailed);
                    Response.Redirect("TableManagement.aspx?tablesAmount=" + tablesAdded + "&tablesFailed=" + tablesFailed);
                }
            }
            catch
            {

            }
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton linkButtonl = (LinkButton)e.Row.FindControl("LinkButton1");
                linkButtonl.Attributes.Add("onclick", "javascript:return " +
                "confirm('Are you sure you want to delete Table No. " +
                DataBinder.Eval(e.Row.DataItem, "table_no") + "?')");
            }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string table_no = e.CommandArgument.ToString();
            if (e.CommandName == "Delete")
            {
                labelStatus.Visible = true;
                labelStatus.Text = DeleteRecordByID(table_no);

            }
            else if (e.CommandName == "Update")
            {
                labelStatus.Visible = true;
                labelStatus.Text = "Table " + table_no + " update successfully.";

            }

        }

        private string DeleteRecordByID(string table_no)
        {
            string r = "";

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            conn.Open();
            cmd.CommandText = "Update Orders set table_no = 'SAMPLE' where table_no = @table_no;";
            cmd.Parameters.AddWithValue("@table_no", table_no);
            int affectedRows = cmd.ExecuteNonQuery();

            r = "Number of orders changed is " + affectedRows;

            return r;
        }

        protected void ddlNewTables_SelectedIndexChanged(object sender, EventArgs e)
        {
            int tablesAdding = Convert.ToInt32(ddlNewTables.SelectedValue);

            Response.Redirect("TableManagement.aspx?table=" + ddlNewTables.SelectedValue);
        }

        protected void buttonManageTables_Click(object sender, EventArgs e)
        {
            Response.Redirect("TableManagement.aspx");
        }

        protected void buttonAllocateTables_Click(object sender, EventArgs e)
        {
            Response.Redirect("TableAllocation.aspx");
        }

        protected void buttonReturn_Click(object sender, EventArgs e)
        {
            Response.Redirect("MainTableManagement.aspx");
        }

        protected void uploadLayout_Click(object sender, EventArgs e)
        {
            lblUploadStatus.Visible = true;
            // Save the uploaded file to an "Uploads" directory
            // that already exists in the file system of the 
            // currently executing ASP.NET application.  
            // Creating an "Uploads" directory isolates uploaded 
            // files in a separate directory. This helps prevent
            // users from overwriting existing application files by
            // uploading files with names like "Web.config".
            string saveDir = @"\Images\";

            // Get the physical file system path for the currently
            // executing application.
            string appPath = Request.PhysicalApplicationPath;

            string savePath = appPath + saveDir;

            // Before attempting to save the file, verify
            // that the FileUpload control contains a file.
            if (FileUploadLayout.HasFile)
            {
                // Get the name of the file to upload.
                string fileName = Server.HtmlEncode(FileUploadLayout.FileName);

                // Get the extension of the uploaded file.
                string extension = System.IO.Path.GetExtension(fileName);

                // Allow only files with .doc or .xls extensions
                // to be uploaded.
                if (fileName.ToLower() == "restauranttablelayout.jpeg" || fileName.ToLower() == "restauranttablelayout.png" || fileName.ToLower() == "restauranttablelayout.jpg")
                {
                    if ((extension.ToLower() == ".jpeg") || (extension.ToLower() == ".png") || (extension.ToLower() == ".jpg"))
                    {

                        if (File.Exists(savePath + fileName) == true)
                        {
                            File.Delete(savePath + fileName);
                        }
                        // Append the name of the file to upload to the path.
                        savePath += fileName;

                        // Call the SaveAs method to save the 
                        // uploaded file to the specified path.
                        // This example does not perform all
                        // the necessary error checking.               
                        // If a file with the same name
                        // already exists in the specified path,  
                        // the uploaded file overwrites it.
                        FileUploadLayout.SaveAs(savePath);
                        Image1.ImageUrl = savePath;

                        // Notify the user that their file was successfully uploaded.
                        Response.Redirect("TableManagement.aspx?photo=true");
                    }

                    else
                    {
                        // Notify the user that an invalid file was selected.
                        lblUploadStatus.Text = "Only .jpeg, .png and .jpg files are accepted.";
                    }
                }
                else
                {
                    // Notify the user that an invalid file was selected.
                    lblUploadStatus.Text = "Please rename the file to 'restaurantTableLayout'.";
                }
            }
            else
            {
                // Notify the user that a file was not uploaded.
                lblUploadStatus.Text = "You did not specify a file to upload.";
            }
            uploadLayout.Focus();
        }

    }
}